package com.nanbei.queue;

import java.util.Iterator;
import java.util.Stack;

/**
 * @ClassDescription: 环形数组实现队列
 * @JdkVersion: 17
 * @Author: BaoShan.li
 * @Created: 2023/11/23 11:17
 */
public class ArrayQueue<E> implements QueueInterface<E>,Iterable<E> {

    private int head = 0;
    private int tail = 0;
    private final E[] array ;
    private final int size;


    @SuppressWarnings("all")
    public ArrayQueue(int capacity) {
        this.size = capacity+1;
        array = (E[]) new Object[this.size];
    }

    @Override
    public boolean offer(E value) {
        if (isFull()){
            return false;
        }
        array[tail] = value;
        tail = (tail+1) % size;

        return true;
    }

    @Override
    public E poll() {
        if (isEmpty()){
            return null;
        }
        E e = array[head];
        head = (head+1) % size;

        return e;
    }

    @Override
    public E peek() {
        if (isEmpty()){
            return null;
        }
        return array[head];
    }

    @Override
    public boolean isEmpty() {
        return head == tail;
    }

    @Override
    public boolean isFull() {
        return (tail+1)%size == head;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {

            int index = head;

            @Override
            public boolean hasNext() {
                return index != tail;
            }

            @Override
            public E next() {
                E e = array[index];
                index = (index+1)%size;
                return e;
            }
        };
    }
}
